\chapter{The UDP Model}
\label{cha:udp}


\section{Overview}

The UDP protocol is a very simple datagram transport protocol, which
basically makes the services of the network layer available to the applications.
It performs packet multiplexing and demultiplexing to ports and some basic
error detection only.

The frame format as described in RFC768:

\begin{center}
\begin{bytefield}{32}
\bitheader{0,7,8,15,16,23,24,31} \\
\bitbox{16}{Source Port} &
\bitbox{16}{Destination Port} \\
\bitbox{16}{Length} &
\bitbox{16}{Checksum} \\
\wordbox{3}{Data}
\end{bytefield}
\end{center}

The ports represents the communication end points that are allocated by the
applications that want to send or receive the datagrams. The ``Data'' field
is the encapsulated application data, the ``Length'' and ``Checksum'' fields
are computed from the data.

The INET framework contains an \nedtype{UDP} module that performs the encapsulation/decapsulation
of user packets, an \nedtype{UDPSocket} class that provides the application the usual
socket interface, and several sample applications.

These components implement the following statndards:
\begin{itemize}
\item RFC768: User Datagram Protocol
\item RFC1122: Requirements for Internet Hosts -- Communication Layers
\end{itemize}

\section{The UDP module}

The UDP protocol is implemented by the \nedtype{UDP} simple module.
There is a module interface (\nedtype{IUDP}) that defines the gates of the
\nedtype{UDP} component. In the \nedtype{StandardHost} node, the UDP component
can be any module implementing that interface.

Each UDP module has gates to connect to the IPv4 and IPv6 network layer
(ipIn/ipOut and ipv6In/ipv6Out), and a gate array to connect to the applications
(appIn/appOut).

The UDP module can be connected to several applications, and each application
can use several sockets to send and receive UDP datagrams.
The state of the sockets are stored within the UDP module and the application
can configure the socket by sending command messages to the UDP module.
These command messages are distinguished by their kind and the type of their
control info. The control info identifies the socket and holds the parameters
of the command.

Applications don't have to send messages directly to the UDP module,
as they can use the \cppclass{UDPSocket} utility class, which encapsulates the messaging and
provides a socket like interface to applications.

\subsection{Sending UDP datagrams}

If the application want to send datagrams, it optionally can connect to the destination.
It does this be sending a message with UDP\_C\_CONNECT kind and \cppclass{UDPConnectCommand}
control info containing the remote address and port of the connection.
The UDP protocol is in fact connectionless, so it does not send any packets as a result
of the connect call. When the UDP module receives the connect request,
it simply remembers the destination address and port and use it as default destination
for later sends. The application can send several connect commands to the same socket.

% FIXME currently connect() or bind() is mandatory as the first command,
%       the application cannot send packets or set options otherwise

% FIXME connect() should allow unspecified dest address and -1 port (interpreted as disconnect())

For sending an UDP packet, the application should attach an \cppclass{UDPSendCommand}
control info to the packet, and send it to \nedtype{UDP}. The control info may contain
the destination address and port. If the destination address or port
is unspecified in the control info then the packet is sent to the connected target.

The \nedtype{UDP} module encapsulates the application's packet into an \msgtype{UDPPacket},
creates an appropriate IP control info and send it over ipOut or ipv6Out depending on
the destination address.

The destination address can be the IPv4 local broadcast address (255.255.255.255)
or a multicast address. Before sending broadcast messages, the socket must be configured
for broadcasting. This is done by sending an message to the UDP module. The message
kind is UDP\_C\_SETOPTION and its control info (an \cppclass{UDPSetBroadcastCommand})
tells if the broadcast is enabled. You can limit the multicast to the local network
by setting the TTL of the IP packets to 1. The TTL can be configured per socket,
by sending a message to the UDP with an \cppclass{UDPSetTimeToLive} control info
containing the value. If the node has multiple interfaces, the application can
choose which is used for multicast messages. This is also a socket option, the
id of the interface (as registered in the interface table) can be given in an
\cppclass{UDPSetMulticastInterfaceCommand} control info.

% FIXME currently sending broadcast messages is enabled without setting SO_BROADCAST to true,
%       this is not so in UNIX

% FIXME there should be a separate TTL for multicast (not used for unicast), default value is 1
%       see IP_MULTICAST_TTL in `man 7 ip`

\begin{note}
The \nedtype{UDP} module supports only local broadcasts (using the special 255.255.255.255 address).
Packages that are broadcasted to a remote subnet are handled as undeliverable messages.
\end{note}

If the UDP packet cannot be delivered because nobody listens on the destination port,
the application will receive a notification about the failure. The notification is
a message with UDP\_I\_ERROR kind having attached an \cppclass{UDPErrorIndication}
control info. The control info contains the local and destination address/port,
but not the original packet.

After the application finished using a socket, it should close it by sending a message
UDP\_C\_CLOSE kind and \cppclass{UDPCloseCommand} control info. The control info
contains only the socket identifier. This command frees the resources associated
with the given socket, for example its socket identifier or bound address/port.

\subsection{Receiving UDP datagrams}

Before receiving UDP datagrams applications should first ``bind'' to the given UDP port.
This can be done by sending a message with message kind UDP\_C\_BIND attached with an
\cppclass{UDPBindCommand} control info. The control info contains the socket identifier
and the local address and port the application want to receive UDP packets.
Both the address and port is optional. If the address is unspecified, than the UDP
packets with any destination address is passed to the application. If the port is
-1, then an unused port is selected automatically by the UDP module.
The localAddress/localPort combination must be unique.

When a packet arrives from the network, first its error bit is checked. Erronous messages
are dropped by the UDP component. Otherwise the application bound to the destination port
is looked up, and the decapsulated packet passed to it. If no application is bound to
the destination port, an ICMP error is sent to the source of the packet. If the socket is
connected, then only those packets are delivered to the application, that received from
the connected remote address and port.

The control info of the decapsulated packet is an \cppclass{UDPDataIndication}
and contains information about the source and destination address/port, the TTL,
and the identifier of the interface card on which the packet was received.

The applications are bound to the unspecified local address, then they receive any packets
targeted to their port. UDP also supports multicast and broadcast addresses; if they
are used as destination address, all nodes in the multicast group or subnet receives the packet.
The socket receives the broadcast packets only if it is configured for broadcast.
To receive multicast messages, the socket must join to the group of the multicast address.
This is done be sending the UDP module an UDP\_C\_SETOPTION message with
\cppclass{UDPJoinMulticastGroupsCommand} control info. The control info specifies the
multicast addresses and the interface identifiers. If the interface identifier is given
only those multicast packets are received that arrived at that interface.
The socket can stop receiving multicast messages if it leaves the multicast group.
For this purpose the application should send the UDP another UDP\_C\_SETOPTION
message in their control info (\cppclass{UDPLeaveMulticastGroupsCommand}) specifying
the multicast addresses of the groups.

% TODO clarify: multicast packets should not be delivered to connected sockets?

\subsection{Signals}

The \nedtype{UDP} module emits the following signals:
\begin{itemize}
  \item \fsignal{sentPk} when an UDP packet sent to the IP, the packet
  \item \fsignal{rcvdPk} when an UDP packet received from the IP, the packet
  \item \fsignal{passedUpPk} when a packet passed up to the application, the packet
  \item \fsignal{droppedPkWrongPort} when an undeliverable UDP packet received, the packet
  \item \fsignal{droppedPkBadChecksum} when an erronous UDP packet received, the packet
\end{itemize}

\section{UDP sockets}

UDPSocket is a convenience class, to make it easier to send and receive
UDP packets from your application models. You'd have one (or more)
UDPSocket object(s) in your application simple module class, and call
its member functions (bind(), connect(), sendTo(), etc.) to create and
configure a socket, and to send datagrams.

UDPSocket chooses and remembers the sockId for you, assembles and sends command
packets such as UDP\_C\_BIND to UDP, and can also help you deal with packets and
notification messages arriving from UDP.

Here is a code fragment that creates an UDP socket and sends a 1K packet
over it (the code can be placed in your handleMessage() or activity()):

\begin{cpp}
UDPSocket socket;
socket.setOutputGate(gate("udpOut"));
socket.connect(L3AddressResolver().resolve("10.0.0.2"), 2000);

cPacket *pk = new cPacket("dgram");
pk->setByteLength(1024);
socket.send(pk);

socket.close();
\end{cpp}

% when the localAddr is unspecified by the socket (~ INADDR_ANY), then the kernel sets the
% source address field of the outgoing packet according to the outgoing interface

Processing messages sent up by the UDP module is relatively straightforward.
You only need to distinguish between data packets and error notifications,
by checking the message kind (should be either UDP\_I\_DATA or UDP\_I\_ERROR),
and casting the control info to UDPDataIndication or UDPErrorIndication.
USPSocket provides some help for this with the \ffunc{belongsToSocket()} and
\ffunc{belongsToAnyUDPSocket()} methods.

\begin{cpp}
void MyApp::handleMessage(cMessage *msg)
{
    if (msg->getKind() == UDP_I_DATA)
    {
        if (socket.belongsToSocket())
            processUDPPacket(PK(msg));
    }
    else if (msg->getKind() == UDP_I_ERROR)
    {
        processUDPError(msg);
    }
    else
    {
        error("Unrecognized message (%s)", msg->getClassName());
    }
}
\end{cpp}

\section{UDP applications}

All UDP applications should be derived from the \nedtype{IUDPApp} module interface,
so that the application of \nedtype{StandardHost} could be configured without changing its NED file.

The following applications are implemented in INET:
\begin{itemize}
\item \nedtype{UDPBasicApp} sends UDP packets to a given IP address at a given interval
\item \nedtype{UDPBasicBurst} sends UDP packets to the given IP address(es) in bursts, or acts as a packet sink.
\item \nedtype{UDPEchoApp} similar to \nedtype{UDPBasicApp}, but it sends back the packet after reception
\item \nedtype{UDPSink} consumes and prints packets received from the \nedtype{UDP} module
\item \nedtype{UDPVideoStreamCli},\nedtype{UDPVideoStreamSvr} simulates UDP streaming
\end{itemize}

The next sections describe these applications in details.

\subsection{UDPBasicApp}

The \nedtype{UDPBasicApp} sends UDP packets to a the IP addresses given in the
\fpar{destAddresses} parameter. The application sends a message to one of the
targets in each \fpar{sendInterval} interval. The interval between message and
the message length can be given as a random variable. Before the packet is
sent, it is emitted in the \fsignal{sentPk} signal.

The application simply prints the received UDP datagrams. The \fsignal{rcvdPk}
signal can be used to detect the received packets.

The number of sent and received messages are saved as scalars at the end of the
simulation.

% could be a simple packet generator without the ability to receive packets?

\subsection{UDPSink}

This module binds an UDP socket to a given local port, and prints the
source and destination and the length of each received packet.

% TODO does not accept broadcast messages

\subsection{UDPEchoApp}

Similar to \nedtype{UDPBasicApp}, but it sends back the packet after reception.
It accepts only packets with \msgtype{UDPEchoAppMsg} type, i.e. packets that
are generated by another \nedtype{UDPEchoApp}.

When an echo response received, it emits an \fsignal{roundTripTime} signal.

\subsection{UDPVideoStreamCli}

This module is a video streaming client. It send one ``video streaming request'' to
the server at time \fpar{startTime} and receives stream from \nedtype{UDPVideoStreamSvr}.

The received packets are emitted by the \fsignal{rcvdPk} signal.

\subsection{UDPVideoStreamSvr}

This is the video stream server to be used with \nedtype{UDPVideoStreamCli}.

The server will wait for incoming "video streaming requests".
When a request arrives, it draws a random video stream size
using the \fpar{videoSize} parameter, and starts streaming to the client.
During streaming, it will send UDP packets of size \fpar{packetLen} at every
\fpar{sendInterval}, until \fpar{videoSize} is reached. The parameters \fpar{packetLen}
and \fpar{sendInterval} can be set to constant values to create CBR traffic,
or to random values (e.g. sendInterval=uniform(1e-6, 1.01e-6)) to
accomodate jitter.

The server can serve several clients, and several streams per client.

% FIXME why streamVector? VideoStreamData could be deleted immediately after last byte sent
% TODO this is video-on-demand, support multicast/broadcast video streaming too

\subsection{UDPBasicBurst}

Sends UDP packets to the given IP address(es) in bursts, or acts as a
packet sink. Compatible with both IPv4 and IPv6.

\subsubsection*{Addressing}

The \fpar{destAddresses} parameter can contain zero, one or more destination
addresses, separated by spaces. If there is no destination address given,
the module will act as packet sink. If there are more than one addresses,
one of them is randomly chosen, either for the whole simulation run,
or for each burst, or for each packet, depending on the value of the
\fpar{chooseDestAddrMode} parameter. The \fpar{destAddrRNG} parameter controls which
(local) RNG is used for randomized address selection.
The own addresses will be ignored.

An address may be given in the dotted decimal notation, or with the module
name. (The \cppclass{L3AddressResolver} class is used to resolve the address.)
You can use the "Broadcast" string as address for sending broadcast messages.

INET also defines several NED functions that can be useful:
\begin{itemize}
\item[-] moduleListByPath("pattern",...): \\
         Returns a space-separated list of the modulenames.
         All modules whole getFullPath() matches one of the pattern parameters will get included.
         The patterns may contain wilcards in the same syntax as in ini files.
         See cTopology::extractByModulePath() function
         example: destaddresses = moduleListByPath("**.host[*]", "**.fixhost[*]")
\item[-] moduleListByNedType("fully.qualified.ned.type",...): \\
         Returns a space-separated list of the modulenames with the given NED type(s).
         All modules whose getNedTypeName() is listed in the given parameters will get included.
         The NED type name is fully qualified.
         See cTopology::extractByNedTypeName() function
         example: destaddresses = moduleListByNedType("inet.nodes.inet.StandardHost")
\end{itemize}

The peer can be UDPSink or another UDPBasicBurst.

\subsubsection*{Bursts}

The first burst starts at \fpar{startTime}. Bursts start by immediately sending
a packet; subsequent packets are sent at \fpar{sendInterval} intervals. The
sendInterval parameter can be a random value, e.g. exponential(10ms).
A constant interval with jitter can be specified as 1s+uniform(-0.01s,0.01s)
or uniform(0.99s,1.01s). The length of the burst is controlled by the
\fpar{burstDuration} parameter. (Note that if \fpar{sendInterval} is greater than
\fpar{burstDuration}, the burst will consist of one packet only.) The time between
burst is the \fpar{sleepDuration} parameter; this can be zero (zero is not
allowed for \fpar{sendInterval}.) The zero \fpar{burstDuration} is interpreted as infinity.

\subsubsection*{Packets}

Packet length is controlled by the \fpar{messageLength} parameter.

The module adds two parameters to packets before sending:
\begin{itemize}
\item[-] sourceID: source module ID
\item[-] msgId: incremented by 1 after send any packet.
\end{itemize}
When received packet has this parameters, the module checks the order of received packets.

\subsubsection*{Operation as sink}

When \fpar{destAddresses} parameter is empty, the module receives packets and makes statistics only.

\subsubsection*{Statistics}

Statistics are collected on outgoing packets:
\begin{itemize}
\item[-] sentPk: packet object
\end{itemize}

Statistics are collected on incoming packets:
\begin{itemize}
\item[-] outOfOrderPk: statistics of out of order packets.
       The packet is out of order, when has msgId and sourceId parameters and module
       received bigger msgId from same sourceID.
\item[-] dropPk: statistics of dropped packets.
       The packet is dropped when not out-of-order packet and delay time is larger than
       delayLimit parameter. The delayLimit=0 is infinity.
\item[-] rcvdPk: statistics of not dropped, not out-of-order packets.
\item[-] endToEndDelay: end to end delay statistics of not dropped, not out-of-order packets.
\end{itemize}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "usman"
%%% End:

